//certificate_add.js @author zlx

const request = require('../../../utils/requestAjax.js')
const app = getApp()
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    checked:true,
    userInfo: {userName:'ww',roleId:1},
    id: '',
    certificate: {},
    //选择文件的list
    tempFilePathList: [],
    certTypeList: [],
    //证书类型是否已选择
    // certTypeIsSelect: false,
    //证书类型选择第几个
    certTypeIndex: -1,
    //起始日期是否已选择
    // beginDateIsSelect: false,
    //终止日期是否已选择
    // endDateIsSelect: false,
    nowDate: '',
    fileList: [],
    imgList: []
  },

  onLoad: function (options) {
    this.setData({
     // userInfo: wx.getStorageSync('userInfo'),
      certTypeList: wx.getStorageSync('baseData')['3'],
      nowDate: app.getNowDate()
    })
  },

  onReady: function () {

  },

  onShow: function () {

  },

  onHide: function () {

  },

  onUnload: function () {

  },

  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.clearAddInput()
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh()
  },

  onReachBottom: function () {

  },

  // onShareAppMessage: function () {

  // },

  //证书类型选择
  bindCertTypePickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      // certTypeIsSelect: true,
      certTypeIndex: e.detail.value,
    })
    this.setData({
      'certificate.certType': this.data.certTypeList[this.data.certTypeIndex].codeDetail
    })
    // console.log(this.data.certificate)
  },

  bindCertNameInput: function (e) {
    this.setData({
      'certificate.certName': e.detail.value
    })
    // console.log(this.data.certificate)
  },

  bindCertIdInput: function (e) {
    this.setData({
      'certificate.certId': e.detail.value
    })
    // console.log(this.data.certificate)
  },

  bindProjectNameInput: function (e) {
    this.setData({
      'certificate.projectName': e.detail.value
    })
    // console.log(this.data.certificate)
  },

  bindCertUnitInput: function (e) {
    this.setData({
      'certificate.certUnit': e.detail.value
    })
    // console.log(this.data.certificate)
  },

  //起始日期选择
  bindBeginDateChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      // beginDateIsSelect: true,
      'certificate.beginDate': e.detail.value
    })
  },

  //终止日期选择
  bindEndDateChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      // endDateIsSelect: true,
      'certificate.endDate': e.detail.value
    })
  },

  bindNoteInput: function (e) {
    this.setData({
      'certificate.note': e.detail.value
    })
    // console.log(this.data.certificate)
  },

  bindTempFileNameInput: function (e) {
    var index = e.currentTarget.dataset.index
    var tempFilePathListIndexKeyName = 'tempFilePathList[' + index + '].name'
    var tempFilePathListIndexKeyFileType = this.data.tempFilePathList[index].name.substring(this.data.tempFilePathList[index].name.lastIndexOf('.'))
    this.setData({
      [tempFilePathListIndexKeyName]: e.detail.value + tempFilePathListIndexKeyFileType
    })
    // console.log(this.data.tempFilePathList)
  },

  bindTempFileNameInputBlur: function (e) {
    var index = e.currentTarget.dataset.index
    let _this = this

    var fileName = _this.data.tempFilePathList[index].name.substring(0, _this.data.tempFilePathList[index].name.lastIndexOf('.'))

    //输入新增附件名为空判断
    if (fileName == '') {
      var tempFilePathListIndexKeyName = 'tempFilePathList[' + index + '].name'
      var tempFilePathListIndexKeyFileType = _this.data.tempFilePathList[index].name.substring(_this.data.tempFilePathList[index].name.lastIndexOf('.'))
      _this.setData({
        [tempFilePathListIndexKeyName]: _this.data.tempFilePathList[index].initFileName + tempFilePathListIndexKeyFileType
      })
      wx.showModal({
        title: '系统提示',
        content: '附件名不能为空，请重新输入',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    //输入新增附件名重复判断
    for (var i = 0; i < _this.data.tempFilePathList.length; i++) {
      var hasTempFilePath = _this.data.tempFilePathList[i]
      if (hasTempFilePath != '') {
        if (hasTempFilePath.name.toLowerCase() == _this.data.tempFilePathList[index].name.toLowerCase() && i != index) {
          var tempFilePathListIndexKeyName = 'tempFilePathList[' + index + '].name'
          var tempFilePathListIndexKeyFileType = _this.data.tempFilePathList[index].name.substring(_this.data.tempFilePathList[index].name.lastIndexOf('.'))
          _this.setData({
            [tempFilePathListIndexKeyName]: _this.data.tempFilePathList[index].initFileName + tempFilePathListIndexKeyFileType
          })

          wx.showModal({
            title: '系统提示',
            content: '新增附件名重复，请重新输入',
            showCancel: false,
            success(res) {
              if (res.confirm) {} else if (res.cancel) {}
            }
          })
        }
      }
    }
  },

  //点击文件＋
  addAttach: function (e) {
    //在最后添加一个元素
    this.data.tempFilePathList.push('')
    //由于上面的方法无法刷新页面 所以需要下面紧跟再setData
    this.setData({
      tempFilePathList: this.data.tempFilePathList
    })
    // console.log(this.data.tempFilePathList)
    wx.pageScrollTo({
      selector: '#save',
      duration: 200
    })
  },
  //点击文件×
  reduceAttach: function (e) {
    //从index开始删除一个元素
    this.data.tempFilePathList.splice(e.currentTarget.dataset.index, 1)
    //由于上面的方法无法刷新页面 所以需要下面紧跟再setData
    this.setData({
      tempFilePathList: this.data.tempFilePathList
    })
    // console.log(this.data.tempFilePathList)
  },

  //点击选择文件
  selectFile: function (e) {
    var index = e.currentTarget.dataset.index
    let _this = this
    wx.chooseMessageFile({
      count: 1,
      success(res) {
        // console.log(res)
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePath = res.tempFiles[0]
        //文件后缀名
        var fileType = tempFilePath.name.substring(tempFilePath.name.lastIndexOf('.') + 1).toLocaleLowerCase()
        if (fileType != 'doc' && fileType != 'docx' && fileType != 'xls' && fileType != 'xlsx' && fileType != 'ppt' && fileType != 'pptx' && fileType != 'pdf' && fileType != 'jpg' && fileType != 'png' && fileType != 'jpeg' && fileType != 'bmp') {
          wx.showModal({
            title: '系统提示',
            content: '不支持的文件类型，请选择文档和图片文件',
            showCancel: false,
            success(res) {
              if (res.confirm) {} else if (res.cancel) {}
            }
          })
          return
        }
        //存在相同文件判断
        var hasSameFileName = false
        for (var i = 0; i < _this.data.tempFilePathList.length; i++) {
          var hasTempFilePath = _this.data.tempFilePathList[i]
          if (hasTempFilePath != '') {
            if (hasTempFilePath.name.toLowerCase() == tempFilePath.name.toLowerCase() && i != index) {
              hasSameFileName = true
              wx.showModal({
                title: '系统提示',
                content: '新增附件名重复，请重新选择',
                showCancel: false,
                success(res) {
                  if (res.confirm) {} else if (res.cancel) {}
                }
              })
            }
          }
        }

        if (hasSameFileName) {
          return
        }
        var tempFilePathListIndexKey = 'tempFilePathList[' + index + ']'
        var tempFilePathListIndexKeyFileName = 'tempFilePathList[' + index + '].initFileName'

        _this.setData({
          [tempFilePathListIndexKey]: tempFilePath,
          [tempFilePathListIndexKeyFileName]: tempFilePath.name.substring(0, tempFilePath.name.lastIndexOf('.'))
        })
        // console.log(_this.data.tempFilePathList)
      }
    })
  },

  //点击保存
  addCertificate: function (e) {

    /*------------校验start------------*/

    if (this.data.certTypeIndex == -1) {
      wx.showModal({
        title: '系统提示',
        content: '证书类型不能为空',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    if (!this.data.certificate.certName) {
      wx.showModal({
        title: '系统提示',
        content: '证书名称不能为空',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    if (!this.data.certificate.certId) {
      wx.showModal({
        title: '系统提示',
        content: '编号不能为空',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    if (!this.data.certificate.projectName) {
      wx.showModal({
        title: '系统提示',
        content: '项目名称不能为空',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    if (!this.data.certificate.certUnit) {
      wx.showModal({
        title: '系统提示',
        content: '颁奖单位不能为空',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    if (!this.data.certificate.beginDate) {
      wx.showModal({
        title: '系统提示',
        content: '发证日期不能为空',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    if (!this.data.certificate.endDate) {
      wx.showModal({
        title: '系统提示',
        content: '到期日期不能为空',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    if (this.data.certificate.beginDate > this.data.certificate.endDate) {
      wx.showModal({
        title: '系统提示',
        content: '发证日期不能大于到期日期',
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return
    }

    /*------------校验end------------*/

    let _this = this

    wx.showModal({
      title: '保存确认',
      content: '确定保存吗？',
      success(res) {
        if (res.confirm) {
          _this.setData({
            'certificate.modifyPerson': _this.data.userInfo.userName
          })
          request.requestAjax("/addCertificate", _this.data.certificate, "正在保存信息",
            //请求成功回调
            function (res) {
              //拿到返回值中的新增的合同id
              // console.log('新增的合同id为：' + res.data.id)
              //开始进行文件上传
              var tempFilePathList = []
              ////深拷贝 同时过滤空文件
              for (var i = 0; i < _this.data.tempFilePathList.length; i++) {
                var tempFilePath = _this.data.tempFilePathList[i]
                if (tempFilePath != '') {
                  tempFilePathList.push(_this.data.tempFilePathList[i])
                }
              }
              if (tempFilePathList.length != 0) {
                // console.log(tempFilePathList)
                //构建Promise.all的参数
                var promiseAllFunList = []
                for (var i = 0; i < tempFilePathList.length; i++) {
                  var tempFilePath = tempFilePathList[i]
                  promiseAllFunList.push(_this.uploadCertificateAttach(tempFilePath, res.data.id, _this.data.userInfo.userName))
                }
                wx.showLoading({
                  title: '正在上传文件',
                  mask: true
                })
                Promise.all(promiseAllFunList)
                  .then(res => {
                    var msg = ''
                    res.forEach(element => {
                      msg += element
                    })
                    if (msg == '') {
                      wx.hideLoading()
                      wx.showModal({
                        title: '系统提示',
                        content: '新增证书成功',
                        showCancel: false,
                        success(res) {
                          if (res.confirm) {
                            wx.navigateBack()
                          } else if (res.cancel) {}
                        }
                      })
                    } else {
                      wx.hideLoading()
                      wx.showModal({
                        title: '系统提示',
                        content: '新增证书成功' + msg,
                        showCancel: false,
                        success(res) {
                          if (res.confirm) {
                            wx.navigateBack()
                          } else if (res.cancel) {}
                        }
                      })
                    }
                  })
                  .catch(e => {
                    wx.hideLoading()
                  })

              } else {
                wx.showModal({
                  title: '系统提示',
                  content: '新增合同成功',
                  showCancel: false,
                  success(res) {
                    if (res.confirm) {
                      wx.navigateBack()
                    } else if (res.cancel) {}
                  }
                })
              }
            },
            //请求失败回调
            function (res) {
              wx.showModal({
                title: '系统提示',
                content: res.msg,
                showCancel: false,
                success(res) {
                  if (res.confirm) {} else if (res.cancel) {}
                }
              })
              // wx.showToast({
              //   title: '保存失败，'+res.msg,
              //   image: '/images/icon_roundclose.png',
              //   duration: 1000,
              //   mask: true
              // })
            })
        } else if (res.cancel) {}
      }
    })
  },

  //上传合同附件
  uploadCertificateAttach: function (tempFilePath, id, modifyPerson) {
    var p = new Promise(function (resolve, reject) {
      var msg = ''
      wx.uploadFile({
        url: app.globalData.urlPrefix + '/uploadCertificateAttach',
        filePath: tempFilePath.path,
        name: 'file',
        formData: {
          //合同id
          'id': id,
          //文件名
          'fileName': tempFilePath.name,
          'modifyPerson': modifyPerson
        },
        //微信的上传文件只要能够访问到服务器 都走success 所以是否成功需要在success中根据后台自定义的code来判断
        success(res) {
          let data = JSON.parse(res.data)
          if (data.code != 200) {
            msg += '，文件：' + tempFilePath.name + ' 上传失败'
          }
          resolve(msg)
        },
        fail(res) {
          msg += '，文件：' + tempFilePath.name + ' 上传失败'
          resolve(msg)
        }
      })
    })
    return p
  },

  clearAddInput: function () {
    this.setData({
      certificate: {},
      tempFilePathList: [],
      // certTypeIsSelect: false,
      certTypeIndex: -1,
      // beginDateIsSelect: false,
      // endDateIsSelect: false,
    })
  },
  GetFileType(path = '') {
    return path.substring(path.lastIndexOf(".") + 1, path.length).toLocaleLowerCase();
  },
  IsImage(name){
    console.log(this.GetFileType(name) === 'png')
    return this.GetFileType(name) === 'png'||
        this.GetFileType(name) === 'jpg' ||
        this.GetFileType(name) === 'jpeg' ||
        this.GetFileType(name) === 'gif'
  },
  ChooseImage() {
    var that = this;
    wx.chooseMessageFile({
      count: 4,
      type: 'all',
      success: (res) => {
        var tempFiles = res.tempFiles.map(item => (
            {
              data:item,
              isImage:that.IsImage(item.path)
            }
        ))
        console.log(tempFiles);
        if (this.data.fileList.length != 0) {
          this.setData({
            // const tempFilePaths = res.tempFilePaths
            fileList: this.data.fileList.concat(tempFiles)
          })
        } else {
          this.setData({
            fileList: tempFiles
          })
        }
      }
    });
  },
  ViewImage(e) {
    console.log(this.data.fileList)
    wx.previewImage({
      urls: this.data.fileList.map(item => item.data.path),
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    this.data.fileList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      fileList: this.data.fileList
    })
  },
  clearAddInput: function () {
    this.setData({
      certificate: {},
      tempFilePathList: [],
      // certTypeIsSelect: false,
      certTypeIndex: -1,
      // beginDateIsSelect: false,
      // endDateIsSelect: false,
    })
  },

})